# sample code demonstrating one way to run an analysis
# and stop it when a given number of faults have been detected

# TODO: first make it work on our own network
# then try to make it feasible for external customers?

# TODO: use the analysis.rb class to define and push the template

require 'libxml_mu'
require 'mu_api'

$DEBUG = false

class Fault_Detector
  
  def initialize(mu_ip, analysis, fault_limit, logfile)
    $testbed_ip = mu_ip
    @doc = XML::Document.file(analysis)
    @posted_uuid = @doc.find_first("//analysis").attributes['uuid']
    @run_uuid = nil
    @fault_limit = fault_limit.to_i
    @logger_file  = logfile # ENV["LOGGER_FILE"] + "/#{$name}.log"
  end

  def do_fault_limit
    fault_limit = 2
    timeout = 400

    # run the analysis, stopping it if the fault limit is reached
    result = go(timeout)
    if result == "fault limit reached"
      puts "stopping test as fault limit #{fault_limit} was reached"
      run_uuid = @doc.find_first("//analysis").attributes['run_uuid']
      @api = Mu_Api.new()
      @api.stop(run_uuid)
      sleep 2
      return
    end
    
    assert(result, "Analysis didn't end within #{timeout} seconds")
  end

  # start the analysis and poll for status and faults
  def go(timeout=120)
    resp = @doc.post
    $DEBUG and puts resp

    if (!resp.find_first("//model_object").attributes["status"] == "success")
      raise Exception.new("Failed to post analysis: #{resp}")
    end

    resp = @doc.run
    $DEBUG and puts resp

    if(resp.find_first("//analysis").attributes['uuid'].nil?)
      raise Exception.new("Failed to run analysis #{resp}")
    end

    sleep 7
    status = @doc.poll_while("RUNNING|QUEUED", timeout, @fault_limit, @logger_file)
    if status == "fault limit reached"
      return status
    end
    
    sleep 7 # allow time for post analysis db cleanup
    return status # should be FINISHED
  end
  
end


if $0 == __FILE__
  unless ARGV[0]
    puts "Usage: #{$0} <mu_ip> <analysis> <fault_limit> <logfile>"
    exit
  end
  mu_ip = ARGV.shift
  analysis = ARGV.shift
  fault_limit = ARGV.shift
  logfile = ARGV.shift
  t = Fault_Detector.new(mu_ip, analysis, fault_limit, logfile)
  t.do_fault_limit
end
